package com.nlgc365.designpattern.Chapter04_Pattern.Creation.P01_Singleton.Usage.Logger;

import java.io.FileWriter;
import java.io.IOException;

public class Logger_singletone {
    private FileWriter fileWriter; //内部有对象级别锁
    private static final Logger_singletone logger;

    static {
        try {
            logger = new Logger_singletone(); //类加载的时候创建该对象, 保证只被创建一次
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private/*这里必须私有*/ Logger_singletone() throws IOException {
        fileWriter = new FileWriter("/path/some.txt");
    }

    //对外提供一个获取单例实例的函数
    public static Logger_singletone getInstance() {
        return logger;
    }

    public void log(String message) {
        try {
            fileWriter.write(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
